package com.cg.design.graphicdesignpattern.interpreter;

import com.cg.design.graphicdesignpattern.interpreter.language.InterpreterFacade;
import com.cg.design.graphicdesignpattern.interpreter.turtle.TurtleCanvas;

import javax.swing.*;
import java.awt.*;

/**
 * Interpreter解释器模式测试类
 *
 * @program: LeetCode->InterpreterTest
 * @author: cg
 * @create: 2022-04-06 09:08
 **/
public class InterpreterTest extends JFrame {

    private final TurtleCanvas canvas = new TurtleCanvas(400, 400);

    private final InterpreterFacade facade = new InterpreterFacade(canvas);

    private final JTextField programTextField = new JTextField("program repeat 4 repeat 3 go right go left end right end end");

    /**
     * 构造函数
     *
     * @param title
     */
    public InterpreterTest(String title) {
        super(title);
        canvas.setExecutor(facade);

        setLayout(new BorderLayout());

        programTextField.addActionListener(e -> {
            if (e.getSource() == programTextField) {
                parseAndExecute();
            }
        });

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        add(programTextField, BorderLayout.NORTH);
        add(canvas, BorderLayout.CENTER);

        pack();
        parseAndExecute();
        show();
    }

    private void parseAndExecute() {
        String programText = programTextField.getText();
        System.out.println("programText = " + programText);
        facade.parse(programText);
        canvas.repaint();
    }

    public static void main(String[] args) {
        new InterpreterTest("Interpreter Pattern!");
    }

}
